package com.meiqiongproperty.yiguanjia.fragment;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.activity.BaseFragmentActivity;
import com.meiqiongproperty.yiguanjia.activity.GenericFragmentActivity;
import com.meiqiongproperty.yiguanjia.fragment.helper.FragmentExchangeConroller;
import com.meiqiongproperty.yiguanjia.fragment.home.h5.H5UserActivity;
import com.meiqiongproperty.yiguanjia.fragment.pay.PaySuccessFragment;
import com.meiqiongproperty.yiguanjia.fragment.pay.WXPayYGJ;
import com.meiqiongproperty.yiguanjia.httpbean.life.LifeWXPay;
import com.meiqiongproperty.yiguanjia.httpbean.order.ShopOrderRepayWXBean;
import com.meiqiongproperty.yiguanjia.httpbean.tenement.pay.CommPayWX;
import com.meiqiongproperty.yiguanjia.httpbean.tenement.pay.WaterWX;
import com.meiqiongproperty.yiguanjia.utils.LogUtil;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.tsy.sdk.pay.alipay.Alipay;
import com.tsy.sdk.pay.weixin.WXPay;

import java.util.Queue;

/**
 * @author Chen
 * @version V1.0
 * @package com.sameway.cnotes.fragment
 * @date 17/1/13
 */
public class BaseFragment extends Fragment {
    protected BaseFragmentActivity baseFragmentActivity;
    private static BaseFragment fragment = new BaseFragment();
    public RequestQueue queue;
    public BaseFragment() {

    }

    public static BaseFragment getInstance() {
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ChangeStatusBar();
        queue = Volley.newRequestQueue(getActivity());// 获取一个请求队列对象
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

//    @Override
//    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
//        super.onActivityCreated(savedInstanceState);
//        try {
//            baseFragmentActivity = (BaseFragmentActivity) getActivity();
//        }catch (Exception e){
//
//        }
//
//    }

    @Override
    public void onResume() {
        super.onResume();
    }

    protected void sendKeyBackEvent() {
        final Context context = getActivity();
        if (context instanceof BaseFragmentActivity) {
            ((BaseFragmentActivity) context).onBackPressed();
        } else if (context instanceof Activity) {
            KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN,
                    KeyEvent.KEYCODE_BACK);
            ((Activity) context).onKeyDown(KeyEvent.KEYCODE_BACK, keyEvent);
        }
    }

    public void ChangeStatusBar() {
        SystemBarTintManager tintManager;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getActivity().getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        tintManager = new SystemBarTintManager(getActivity());
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(R.color.transparent);//通知栏所需颜色
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
    }

    /**
     * 获取页面className
     *
     * @return
     */
    public String getTagName() {
        return BaseFragment.this.getClass().getName();
    }

    /**
     * 销毁当前页面
     */
    public void dismissSelf() {
        FragmentExchangeConroller
                .removeFragment(getFragmentManager(), this);
    }

    public interface OnActivityResultListener {
        void onActivityResult(FragmentActivity activity, int reqCode, int resCode, Intent data);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @TargetApi(19)
    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }

    /**
     * 支付宝支付
     *
     * @param pay_param 支付服务生成的支付参数
     */
    public void doAlipay(String pay_param) {
        new Alipay(getActivity(), pay_param, new Alipay.AlipayResultCallBack() {
            @Override
            public void onSuccess() {
                GenericFragmentActivity.start(getActivity(), PaySuccessFragment.class,new Bundle());
                Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDealing() {
                Toast.makeText(getActivity(), "支付处理中...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case Alipay.ERROR_RESULT:
                        Toast.makeText(getActivity(), "支付失败:支付结果解析错误", Toast.LENGTH_SHORT).show();
                        break;

                    case Alipay.ERROR_NETWORK:
                        Toast.makeText(getActivity(), "支付失败:网络连接错误", Toast.LENGTH_SHORT).show();
                        break;

                    case Alipay.ERROR_PAY:
                        Toast.makeText(getActivity(), "支付错误:支付码支付失败", Toast.LENGTH_SHORT).show();
                        break;

                    default:
                        Toast.makeText(getActivity(), "支付错误", Toast.LENGTH_SHORT).show();
                        break;
                }

            }

            @Override
            public void onCancel() {
                Toast.makeText(getActivity(), "支付取消", Toast.LENGTH_SHORT).show();
            }
        }).doPay();
    }

    /**
     * 微信支付
     *
     * @param pay_param 支付服务生成的支付参数
     */
    public void doWXPay(CommPayWX.ParameterBeanX.ParameterBean pay_param, String wx_appid) {
//        String wx_appid = wx_appid;     //替换为自己的appid
        LogUtil.d("pay_param=" + pay_param.toString());
        WXPayYGJ.init(getActivity(), wx_appid);
        //要在支付前调用
        WXPayYGJ.getInstance().doPay(pay_param, new WXPayYGJ.WXPayYGJResultCallBack() {
            @Override
            public void onSuccess() {
                GenericFragmentActivity.start(getActivity(), PaySuccessFragment.class,new Bundle());
                Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:
                        Toast.makeText(getActivity(), "未安装微信或微信版本过低", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY_PARAM:
                        Toast.makeText(getActivity(), "参数错误", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY:
                        Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onCancel() {
                Toast.makeText(getActivity(), "支付取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 微信支付 生活服务
     *
     * @param pay_param 支付服务生成的支付参数
     */
    public void doLifeWXPay(LifeWXPay.ParameterBeanLifeX.ParameterBean pay_param, String wx_appid) {
//        String wx_appid = wx_appid;     //替换为自己的appid
        LogUtil.d("pay_param=" + pay_param.toString());
        WXPayYGJ.init(getActivity(), wx_appid);
        //要在支付前调用
        WXPayYGJ.getInstance().doLifePay(pay_param, new WXPayYGJ.WXPayYGJResultCallBack() {
            @Override
            public void onSuccess() {
                GenericFragmentActivity.start(getActivity(), PaySuccessFragment.class,new Bundle());
                Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:
                        Toast.makeText(getActivity(), "未安装微信或微信版本过低", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY_PARAM:
                        Toast.makeText(getActivity(), "参数错误", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY:
                        Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onCancel() {
                Toast.makeText(getActivity(), "支付取消", Toast.LENGTH_SHORT).show();
            }
        });
    }


    /**
     * 微信支付 商城订单重新支付
     *
     * @param pay_param 支付服务生成的支付参数
     */
    public void doShopOrderWXPay(ShopOrderRepayWXBean.ParameterBeanX.ParameterBean pay_param, String wx_appid) {
//        String wx_appid = wx_appid;     //替换为自己的appid
        LogUtil.d("pay_param=" + pay_param.toString());
        WXPayYGJ.init(getActivity(), wx_appid);
        //要在支付前调用
        WXPayYGJ.getInstance().doShopOrderRepay(pay_param, new WXPayYGJ.WXPayYGJResultCallBack() {
            @Override
            public void onSuccess() {
                GenericFragmentActivity.start(getActivity(), PaySuccessFragment.class,new Bundle());
                Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:
                        Toast.makeText(getActivity(), "未安装微信或微信版本过低", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY_PARAM:
                        Toast.makeText(getActivity(), "参数错误", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY:
                        Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onCancel() {
                Toast.makeText(getActivity(), "支付取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 微信支付 水费重新支付
     *
     * @param pay_param 支付服务生成的支付参数
     */

    public void doWaterOrderWXPay(WaterWX.ParameterBeanX.ParameterBean pay_param, String wx_appid) {
//        String wx_appid = wx_appid;     //替换为自己的appid
        LogUtil.d("pay_param=" + pay_param.toString());
        WXPayYGJ.init(getActivity(), wx_appid);
        //要在支付前调用
        WXPayYGJ.getInstance().doWaterOrderRepay(pay_param, new WXPayYGJ.WXPayYGJResultCallBack() {
            @Override
            public void onSuccess() {
                GenericFragmentActivity.start(getActivity(), PaySuccessFragment.class,new Bundle());
                Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:
                        Toast.makeText(getActivity(), "未安装微信或微信版本过低", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY_PARAM:
                        Toast.makeText(getActivity(), "参数错误", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY:
                        Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onCancel() {
                Toast.makeText(getActivity(), "支付取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void toH5(String url, String title) {
        Intent i = new Intent();
        i.putExtra(H5UserActivity.URL, url);
        i.putExtra(H5UserActivity.TITLE, title);
        i.setClass(getActivity(), H5UserActivity.class);
        startActivity(i);
    }
}
